import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import { http } from '@/utils/request'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(Cookies.get('token') || '')
  const userInfo = ref(null)
  const loading = ref(false)
  const initialized = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    Cookies.set('token', newToken, { expires: 7 }) // 7天过期
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
    Cookies.remove('token')
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  // 登录
  const login = async (credentials) => {
    loading.value = true
    try {
      const response = await http.post('/auth/login', credentials)
      const { token: newToken, username } = response.data

      setToken(newToken)
      setUserInfo({ username })
      initialized.value = true

      return Promise.resolve(response)
    } catch (error) {
      return Promise.reject(error)
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await http.post('/auth/logout')
      }
    } catch (error) {
      console.warn('登出请求失败:', error.message)
    } finally {
      // 无论请求是否成功，都清除本地状态
      clearToken()
      setUserInfo(null)
      initialized.value = false
    }
  }

  // 验证token
  const verifyToken = async () => {
    if (!token.value) {
      return false
    }

    try {
      const response = await http.get('/auth/verify')
      setUserInfo(response.data)
      return true
    } catch (error) {
      // token无效，清除本地状态
      clearToken()
      setUserInfo(null)
      initialized.value = false
      return false
    }
  }

  // 检查登录状态
  const checkLoginStatus = async () => {
    if (!token.value) {
      initialized.value = true
      setUserInfo(null)
      return false
    }

    if (!initialized.value || !userInfo.value) {
      const isValid = await verifyToken()
      initialized.value = true
      if (!isValid) {
        return false
      }
    }

    return true
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const response = await http.post('/auth/refresh')
      const { token: newToken } = response.data
      setToken(newToken)
      return true
    } catch (error) {
      logout()
      return false
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    loading.value = true
    try {
      const response = await http.post('/auth/change-password', passwordData)
      return Promise.resolve(response)
    } catch (error) {
      return Promise.reject(error)
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    token,
    userInfo,
    loading,
    initialized,

    // 计算属性
    isAuthenticated,

    // 方法
    setToken,
    clearToken,
    setUserInfo,
    login,
    logout,
    verifyToken,
    checkLoginStatus,
    refreshToken,
    changePassword
  }
})
